package wblog.web;

import cn.webwheel.DefaultAction;
import com.google.inject.Inject;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import wblog.domain.User;
import wblog.service.LoginUserService;

import java.sql.SQLException;

abstract public class BaseAction extends DefaultAction {

    public int pg = 1;

    @Inject
    protected QueryRunner qr;

    @Inject
    protected LoginUserService loginUserService;

    private User loginUser;

    protected int itemCount = 0;

    protected int pageSize = 2;

    public User getLoginUser() throws SQLException {
        if (loginUser != null) return loginUser;
        String uid = loginUserService.getLoginUserId();
        if (uid == null) return null;
        return loginUser = qr.query("select * from User where id=?", new BeanHandler<User>(User.class), uid);
    }

    public int[] getPgs() {
        int b = pg - 5;
        int e = pg + 5;
        while (b < 1) {
            b++;
            e++;
        }
        while (e > getPageCount()) {
            e--;
        }
        int[] pgs = new int[e - b + 1];
        for (int i = 0; i < pgs.length; i++) {
            pgs[i] = b + i;
        }
        return pgs;
    }

    public int getItemCount() {
        return itemCount;
    }

    public int getPageCount() {
        if (itemCount == 0) return 1;
        return (itemCount + pageSize - 1) / pageSize;
    }

    public int getPageSize() {
        return pageSize;
    }
}
